﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AutoupdateClient.Mgr
{
    using System.IO;
    using System.Diagnostics;

    internal class ConfigMgr
    {
        #region Instance

        public static ConfigMgr instance { set; get; } = null;

        public static ConfigMgr getInstance()
        {
            if (instance == null)
            {
                instance = new ConfigMgr();
            }

            return instance;
        }

        #endregion

        public Model.Config config { private set; get; } = null;

        public void Load()
        {
            string configFile = Environment.CurrentDirectory + "\\Application.properties";

            Console.WriteLine(configFile);

            if (File.Exists(configFile))
            {
                string[] strLines = File.ReadAllLines(configFile, Encoding.UTF8);

                if (this.config == null)
                    this.config = new Model.Config();

                foreach (string line in strLines)
                {
                    string lin = line.Trim();

                    if (lin.StartsWith("#"))
                    {
                        continue;
                    }

                    if (lin.StartsWith("serverPort="))
                    {
                        this.config.serverPort = this.stringToInt(lin.Replace("serverPort=", "").Trim());
                    }
                    if (lin.StartsWith("serverAddress="))
                    {
                        this.config.serverAddress = lin.Replace("serverAddress=", "").Trim();
                    }
                    //TOPIC=
                    if (lin.StartsWith("executePath="))
                    {
                        this.config.executePath = lin.Replace("executePath=", "").Trim();
                        Console.WriteLine(this.config.executePath);
                    }
                    if (lin.StartsWith("executeFile="))
                    {
                        this.config.executeFile = lin.Replace("executeFile=", "").Trim();
                    }
                }
            }
        }

        private int stringToInt(string value)
        {
            int result = 0;
            try
            {
                result = int.Parse(value);
            }
            catch (Exception ex)
            {
                result = 1314;
            }
            return result;
        }
    }
}
